{% extends 'base.html' %}
{% load static %}
{% load story_tags %}

{% block title %}{{ story.title }} - AI故事生成系统{% endblock %}

{% block extra_css %}
<style>
    /* 故事详情页样式 */
    .story-header {
        position: relative;
        padding: 2.5rem 0;
        margin-bottom: 2rem;
        border-bottom: 1px solid rgba(0,0,0,0.05);
    }
    
    .story-header h1 {
        font-size: 2.5rem;
        font-weight: 700;
        line-height: 1.3;
        color: var(--dark-color);
        margin-bottom: 1rem;
    }
    
    .story-meta {
        color: #6c757d;
        margin-bottom: 1.5rem;
    }
    
    .story-meta a {
        color: var(--primary-color);
        text-decoration: none;
        transition: all 0.2s ease;
    }
    
    .story-meta a:hover {
        text-decoration: underline;
    }
    
    .story-keywords {
        margin-bottom: 1.5rem;
    }
    
    .story-keywords .badge {
        margin-right: 0.5rem;
        font-size: 0.85rem;
        padding: 0.5em 0.8em;
        background-color: #f8f9fa;
        color: #495057;
        border: 1px solid #e9ecef;
        transition: all 0.3s ease;
    }
    
    .story-keywords .badge:hover {
        background-color: var(--primary-color);
        color: white;
        border-color: var(--primary-color);
    }
    
    .story-content {
        font-family: 'Noto Serif', 'Times New Roman', serif;
        font-size: 1.1rem;
        line-height: 1.8;
        color: #333;
        margin-bottom: 2rem;
        padding: 0 0.5rem;
    }
    
    .story-content p {
        margin-bottom: 1.5rem;
    }
    
    .story-actions {
        padding: 1.5rem;
        background-color: #f8f9fa;
        border-radius: 10px;
        margin-bottom: 2rem;
        transition: all 0.3s ease;
    }
    
    .story-actions:hover {
        box-shadow: 0 5px 15px rgba(0,0,0,0.05);
    }
    
    .action-btn {
        position: relative;
        border-radius: 8px;
        font-weight: 500;
        transition: all 0.3s ease;
    }
    
    .action-btn:hover {
        transform: translateY(-2px);
    }
    
    .action-btn .badge {
        position: absolute;
        top: -8px;
        right: -8px;
        font-size: 0.75rem;
    }
    
    .comments-card {
        border-radius: 10px;
        overflow: hidden;
        box-shadow: 0 5px 15px rgba(0,0,0,0.05);
    }
    
    .comments-header {
        padding: 1.5rem;
        background-color: #f8f9fa;
        border-bottom: 1px solid rgba(0,0,0,0.05);
    }
    
    .comments-header h3 {
        margin-bottom: 0;
        font-weight: 600;
        color: var(--dark-color);
    }
    
    .comment-form {
        padding: 1.5rem;
        background-color: #f9f9f9;
        border-bottom: 1px solid rgba(0,0,0,0.05);
    }
    
    .comment-list {
        padding: 1.5rem;
    }
    
    .comment {
        padding: 1.2rem;
        border-radius: 8px;
        background-color: #f9f9f9;
        transition: all 0.3s ease;
    }
    
    .comment:hover {
        box-shadow: 0 3px 10px rgba(0,0,0,0.05);
        background-color: #f5f5f5;
    }
    
    .comment-avatar {
        border: 2px solid #fff;
        box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    }
    
    .comment-username {
        font-weight: 600;
        color: var(--dark-color);
    }
    
    .comment-content {
        font-size: 1rem;
        line-height: 1.5;
    }
    
    .reply {
        background-color: #f5f5f5;
        border-radius: 8px;
        padding: 1rem;
        transition: all 0.3s ease;
    }
    
    .reply:hover {
        background-color: #f0f0f0;
    }
    
    .action-feedback {
        display: inline-block;
        padding: 0.3rem 0.8rem;
        border-radius: 30px;
        background-color: rgba(0,0,0,0.05);
        transition: all 0.3s ease;
    }
    
    /* 动画效果 */
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    
    .animate-fade-in {
        animation: fadeIn 0.5s ease forwards;
    }
    
    /* 响应式调整 */
    @media (max-width: 768px) {
        .story-header h1 {
            font-size: 2rem;
        }
        
        .story-content {
            font-size: 1rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row justify-content-center">
        <div class="col-lg-9">
            <!-- 故事内容卡片 -->
            <div class="card border-0 shadow-sm mb-4 animate-fade-in">
                <div class="card-body p-0">
                    <div class="story-header px-4">
                        <h1>{{ story.title }}</h1>
                        <div class="story-meta">
                            <span><i class="bi bi-person-circle me-1"></i> 作者：<a href="{% url 'user:user_profile' story.author.username %}">{{ story.author.username }}</a></span>
                            <span class="ms-3"><i class="bi bi-tag me-1"></i> 分类：{{ story.get_category_display }}</span>
                            <span class="ms-3"><i class="bi bi-calendar me-1"></i> 发布于：{{ story.created_at|date:"Y-m-d H:i" }}</span>
                            {% if story.updated_at != story.created_at %}
                            <span class="ms-3"><i class="bi bi-pencil me-1"></i> 更新于：{{ story.updated_at|date:"Y-m-d H:i" }}</span>
                            {% endif %}
                            <span class="ms-3"><i class="bi bi-eye me-1"></i> 浏览：{{ story.views }}</span>
                            <span class="ms-3"><i class="bi bi-heart me-1"></i> 点赞：<span id="likes-count">{{ story.likes }}</span></span>
                        </div>
                        
                        {% if story.keywords %}
                        <div class="story-keywords">
                            {% for keyword in story.keywords.split %}
                            <span class="badge rounded-pill">{{ keyword }}</span>
                            {% endfor %}
                        </div>
                        {% endif %}
                        
                        {% if user == story.author %}
                        <div class="text-end mb-3">
                            <a href="{% url 'story:edit' story.pk %}" class="btn btn-outline-primary btn-sm">
                                <i class="bi bi-pencil-square me-1"></i> 编辑故事
                            </a>
                            <a href="{% url 'story:delete' story.pk %}" class="btn btn-outline-danger btn-sm ms-2">
                                <i class="bi bi-trash me-1"></i> 删除故事
                            </a>
                        </div>
                        {% endif %}
                    </div>
                    
                    <div class="story-content p-4">
                        {{ story.content|safe }}
                    </div>
                    
                    <div class="story-actions">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <button id="like-btn" class="btn btn-outline-primary action-btn me-2" data-story-id="{{ story.pk }}">
                                    {% if user_liked %}
                                    <i class="bi bi-heart-fill"></i>
                                    {% else %}
                                    <i class="bi bi-heart"></i>
                                    {% endif %}
                                    <span class="ms-1">点赞</span>
                                    <span id="likes-badge" class="badge bg-danger">
                                        {{ story.likes }}
                                    </span>
                                </button>
                                <button id="favorite-btn" class="btn btn-outline-warning action-btn me-2" data-story-id="{{ story.pk }}">
                                    {% if user_favorited %}
                                    <i class="bi bi-star-fill"></i>
                                    {% else %}
                                    <i class="bi bi-star"></i>
                                    {% endif %}
                                    <span class="ms-1">收藏</span>
                                </button>
                                <div class="dropdown d-inline-block">
                                    <button class="btn btn-outline-success action-btn dropdown-toggle" type="button" id="shareDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                                        <i class="bi bi-share"></i> 分享
                                    </button>
                                    <ul class="dropdown-menu shadow-sm" aria-labelledby="shareDropdown">
                                        <li>
                                            <a class="dropdown-item" href="https://service.weibo.com/share/share.php?url={{ request.build_absolute_uri }}&title={{ story.title }} - AI故事生成系统" target="_blank">
                                                <i class="bi bi-sina-weibo text-danger me-2"></i> 分享到微博
                                            </a>
                                        </li>
                                        <li>
                                            <a class="dropdown-item" href="https://www.facebook.com/sharer/sharer.php?u={{ request.build_absolute_uri }}" target="_blank">
                                                <i class="bi bi-facebook text-primary me-2"></i> 分享到Facebook
                                            </a>
                                        </li>
                                        <li>
                                            <a class="dropdown-item" href="https://twitter.com/intent/tweet?url={{ request.build_absolute_uri }}&text={{ story.title }} - AI故事生成系统" target="_blank">
                                                <i class="bi bi-twitter text-info me-2"></i> 分享到Twitter
                                            </a>
                                        </li>
                                        <li>
                                            <a class="dropdown-item" href="https://t.me/share/url?url={{ request.build_absolute_uri }}&text={{ story.title }} - AI故事生成系统" target="_blank">
                                                <i class="bi bi-telegram text-info me-2"></i> 分享到Telegram
                                            </a>
                                        </li>
                                        <li><hr class="dropdown-divider"></li>
                                        <li>
                                            <button class="dropdown-item" id="copy-link-btn" data-url="{{ request.build_absolute_uri }}">
                                                <i class="bi bi-link-45deg me-2"></i> 复制链接
                                            </button>
                                        </li>
                                    </ul>
                                </div>
                                <span id="action-feedback" class="action-feedback ms-2" style="opacity: 0;"></span>
                            </div>
                            <button class="btn btn-outline-danger action-btn" data-bs-toggle="modal" data-bs-target="#reportModal">
                                <i class="bi bi-flag"></i> 举报
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 评论区 -->
            <div class="comments-card animate-fade-in" style="animation-delay: 0.2s;">
                <div class="comments-header">
                    <h3><i class="bi bi-chat-dots me-2"></i>评论区</h3>
                </div>
                
                {% if user.is_authenticated %}
                <div class="comment-form">
                    {% csrf_token %}
                    <label for="commentContent" class="form-label fw-bold">发表评论</label>
                    <textarea class="form-control mb-2" id="commentContent" rows="3" placeholder="分享您的想法..."></textarea>
                    <div id="commentFeedback" class="invalid-feedback mb-2"></div>
                    <button class="btn btn-primary" id="submitComment">
                        <i class="bi bi-send me-1"></i> 提交评论
                    </button>
                    <span class="text-muted small ms-2">评论将在审核后显示</span>
                </div>
                {% else %}
                <div class="p-4 text-center bg-light">
                    <i class="bi bi-lock me-2 fs-3 text-muted"></i>
                    <p class="mb-2">请<a href="{% url 'user:login' %}?next={{ request.path }}" class="fw-bold">登录</a>后发表评论</p>
                    <a href="{% url 'user:login' %}?next={{ request.path }}" class="btn btn-primary btn-sm">
                        <i class="bi bi-box-arrow-in-right me-1"></i> 立即登录
                    </a>
                </div>
                {% endif %}
                
                <div class="comment-list" id="commentsContainer">
                    <div class="text-center py-4">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <p class="mt-2 text-muted">正在加载评论...</p>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 侧边栏 - 可以考虑添加推荐故事或相关信息 -->
        <div class="col-lg-3 d-none d-lg-block">
            <!-- 作者信息 -->
            <div class="card shadow-sm mb-4 animate-fade-in" style="animation-delay: 0.3s;">
                <div class="card-header bg-light">
                    <h5 class="mb-0"><i class="bi bi-person me-2"></i>作者信息</h5>
                </div>
                <div class="card-body text-center">
                    {% if story.author.profile and story.author.profile.avatar %}
                    <img src="{{ story.author.profile.avatar.url }}" class="rounded-circle mb-3" width="80" height="80" alt="{{ story.author.username }}">
                    {% else %}
                    <img src="{% static 'admin/img/tx.png' %}" class="rounded-circle mb-3" width="80" height="80" alt="{{ story.author.username }}">
                    {% endif %}
                    <h5>{{ story.author.username }}</h5>
                    <p class="text-muted small">{{ story.author.profile.bio|default:"这个人很懒，什么都没留下" }}</p>
                    <a href="{% url 'user:user_profile' story.author.username %}" class="btn btn-sm btn-outline-primary w-100">
                        <i class="bi bi-journal-text me-1"></i> 查看更多作品
                    </a>
                </div>
            </div>
            
            <!-- 故事信息 -->
            <div class="card shadow-sm mb-4 animate-fade-in" style="animation-delay: 0.4s;">
                <div class="card-header bg-light">
                    <h5 class="mb-0"><i class="bi bi-info-circle me-2"></i>故事信息</h5>
                </div>
                <div class="card-body">
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-eye me-2"></i>浏览量</span>
                            <span class="badge bg-primary rounded-pill">{{ story.views }}</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-heart me-2"></i>点赞数</span>
                            <span class="badge bg-danger rounded-pill">{{ story.likes }}</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-calendar me-2"></i>发布日期</span>
                            <span>{{ story.created_at|date:"Y-m-d" }}</span>
                        </li>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <span><i class="bi bi-tag me-2"></i>分类</span>
                            <a href="{% url 'story:list' %}?category={{ story.category.id }}" class="text-decoration-none">
                                {{ story.get_category_display }}
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 举报对话框 -->
<div class="modal fade" id="reportModal" tabindex="-1" aria-labelledby="reportModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="reportModalLabel"><i class="bi bi-flag me-2"></i>举报故事</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="post" action="{% url 'story:report' story.pk %}">
                {% csrf_token %}
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="report_type" class="form-label">举报原因</label>
                        <select name="report_type" id="report_type" class="form-select" required>
                            <option value="">请选择举报原因</option>
                            <option value="spam">垃圾信息</option>
                            <option value="inappropriate">不当内容</option>
                            <option value="copyright">版权问题</option>
                            <option value="other">其他</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">详细说明</label>
                        <textarea name="description" id="description" class="form-control" rows="3" placeholder="请详细描述问题，以便我们进行处理..." required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-danger">
                        <i class="bi bi-send me-1"></i> 提交举报
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 评论回复模板 -->
<template id="reply-template">
    <div class="mb-3 reply-form" style="display:none;">
        <label class="form-label fw-bold">回复评论</label>
        <textarea class="form-control reply-content mb-2" rows="2" placeholder="输入您的回复..."></textarea>
        <div class="reply-feedback invalid-feedback mb-2"></div>
        <div class="d-flex">
            <button class="btn btn-sm btn-primary submit-reply">
                <i class="bi bi-send me-1"></i> 提交回复
            </button>
            <button class="btn btn-sm btn-secondary ms-2 cancel-reply">
                <i class="bi bi-x me-1"></i> 取消
            </button>
        </div>
        <div class="text-muted small mt-1">回复将在审核后显示</div>
    </div>
</template>

<!-- 评论模板 -->
<template id="comment-template">
    <div class="comment mb-3">
        <div class="d-flex">
            <div class="flex-shrink-0">
                <img src="{% static 'admin/img/tx.png' %}" class="rounded-circle me-2 comment-avatar" width="40" height="40" alt="用户头像">
            </div>
            <div class="flex-grow-1">
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <h6 class="mb-0 comment-username"></h6>
                    <small class="text-muted comment-time"></small>
                </div>
                <p class="comment-content mb-2"></p>
                <div class="d-flex align-items-center">
                    {% if user.is_authenticated %}
                    <button class="btn btn-sm btn-outline-secondary reply-btn me-2">
                        <i class="bi bi-reply me-1"></i> 回复
                    </button>
                    <button class="btn btn-sm btn-outline-danger comment-like-btn">
                        <i class="bi bi-heart"></i>
                        <span class="ms-1 comment-like-count">0</span>
                    </button>
                    {% endif %}
                </div>
                <div class="reply-container mt-2"></div>
                <div class="reply-form-container mt-2"></div>
            </div>
        </div>
    </div>
</template>

<!-- JavaScript 处理评论功能 -->
<script>
  var storyId = "{{ story.id|default:'null' }}";
  if (storyId === "null") {
    storyId = null;
  } else {
    storyId = parseInt(storyId);
  }
  
  document.addEventListener('DOMContentLoaded', function() {
    // 加载评论
    function loadComments() {
        const commentsContainer = document.getElementById('commentsContainer');
        
        fetch(`/interactive/story/${storyId}/comments/`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应异常');
                }
                return response.json();
            })
            .then(data => {
                commentsContainer.innerHTML = '';
                
                if (!data.comments || data.comments.length === 0) {
                    commentsContainer.innerHTML = `
                        <div class="text-center my-4">
                            <i class="bi bi-chat-square-text text-muted" style="font-size: 2rem;"></i>
                            <p class="text-muted mt-2">还没有人评论，来发表第一条评论吧！</p>
                        </div>
                    `;
                    return;
                }
                
                data.comments.forEach(comment => {
                    const commentElement = createCommentElement(comment);
                    commentsContainer.appendChild(commentElement);
                });
            })
            .catch(error => {
                console.error('加载评论失败:', error);
                commentsContainer.innerHTML = `
                    <div class="alert alert-danger text-center">
                        <i class="bi bi-exclamation-triangle me-2"></i>评论加载失败，请刷新页面重试
                    </div>
                `;
            });
    }
    
    // 创建评论元素
    function createCommentElement(comment) {
        const template = document.getElementById('comment-template');
        const commentElement = document.importNode(template.content, true).firstElementChild;
        
        commentElement.setAttribute('data-comment-id', comment.id);
        
        // 设置用户头像
        const avatarImg = commentElement.querySelector('.comment-avatar');
        if (avatarImg) {
            // 头像URL已经在API中处理好，直接使用
            avatarImg.src = comment.user.avatar || '{% static "admin/img/tx.png" %}';
            avatarImg.alt = `${comment.user.username}的头像`;
        }
        
        commentElement.querySelector('.comment-username').textContent = comment.user.username;
        commentElement.querySelector('.comment-time').textContent = comment.created_at;
        commentElement.querySelector('.comment-content').textContent = comment.content;
        
        // 设置点赞计数和按钮状态
        const likeBtn = commentElement.querySelector('.comment-like-btn');
        const likeCount = commentElement.querySelector('.comment-like-count');
        if (likeCount) {
            likeCount.textContent = comment.likes_count || 0;
        }
        
        // 添加点赞按钮事件
        if (likeBtn) {
            likeBtn.setAttribute('data-comment-id', comment.id);
            likeBtn.addEventListener('click', function() {
                likeComment(comment.id);
            });
        }
        
        // 添加回复按钮事件
        const replyBtn = commentElement.querySelector('.reply-btn');
        if (replyBtn) {
            replyBtn.addEventListener('click', function() {
                setupReplyForm(commentElement, comment.id);
            });
        }
        
        // 添加评论的回复
        const replyContainer = commentElement.querySelector('.reply-container');
        if (comment.replies && comment.replies.length > 0) {
            comment.replies.forEach(reply => {
                const replyElement = document.createElement('div');
                replyElement.className = 'reply ms-4 mt-2 border-start border-2 ps-2';
                
                replyElement.innerHTML = `
                    <div class="d-flex">
                        <div class="flex-shrink-0">
                            <img src="${reply.user.avatar || '{% static "admin/img/tx.png" %}'}" class="rounded-circle me-2" width="30" height="30" alt="${reply.user.username}的头像">
                        </div>
                        <div class="flex-grow-1">
                            <div class="d-flex justify-content-between">
                                <h6 class="mb-0 small">${reply.user.username}</h6>
                                <small class="text-muted">${reply.created_at}</small>
                            </div>
                            <p class="mb-0 small">${reply.content}</p>
                        </div>
                    </div>
                `;
                replyContainer.appendChild(replyElement);
            });
        }
        
        return commentElement;
    }
    
    // 设置回复表单
    function setupReplyForm(commentElement, commentId) {
        // 清除其他回复表单
        document.querySelectorAll('.reply-form').forEach(form => {
            if (form.style.display === 'block') {
                form.style.display = 'none';
                form.parentElement.innerHTML = '';
            }
        });
        
        const formContainer = commentElement.querySelector('.reply-form-container');
        const template = document.getElementById('reply-template');
        const replyForm = document.importNode(template.content, true).firstElementChild;
        
        formContainer.innerHTML = '';
        formContainer.appendChild(replyForm);
        replyForm.style.display = 'block';
        
        // 取消回复按钮
        replyForm.querySelector('.cancel-reply').addEventListener('click', function() {
            formContainer.innerHTML = '';
        });
        
        // 提交回复按钮
        replyForm.querySelector('.submit-reply').addEventListener('click', function() {
            const content = replyForm.querySelector('.reply-content').value.trim();
            const feedbackElement = replyForm.querySelector('.reply-feedback');
            
            if (!content) {
                feedbackElement.textContent = '回复内容不能为空';
                replyForm.querySelector('.reply-content').classList.add('is-invalid');
                return;
            }
            
            submitComment(content, commentId, replyForm);
        });
    }
    
    // 提交评论或回复
    function submitComment(content, parentId = null, replyForm = null) {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        
        fetch(`/interactive/story/${storyId}/comment/`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrfToken
            },
            body: JSON.stringify({
                content: content,
                parent_id: parentId
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('提交评论失败，请重试');
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                if (replyForm) {
                    replyForm.style.display = 'none';
                    replyForm.parentElement.innerHTML = '<div class="alert alert-success mt-2">回复已提交，等待审核</div>';
                    setTimeout(() => {
                        replyForm.parentElement.innerHTML = '';
                    }, 2000);
                } else {
                    document.getElementById('commentContent').value = '';
                    document.getElementById('commentFeedback').textContent = '';
                    document.getElementById('commentContent').classList.remove('is-invalid');
                    
                    // 显示提交成功消息
                    const successAlert = document.createElement('div');
                    successAlert.className = 'alert alert-success mt-2';
                    successAlert.textContent = '评论已提交，等待审核';
                    document.getElementById('commentContent').parentElement.appendChild(successAlert);
                    
                    setTimeout(() => {
                        successAlert.remove();
                    }, 2000);
                }
            } else {
                const errorMessage = data.message || '提交失败，请重试';
                if (replyForm) {
                    replyForm.querySelector('.reply-feedback').textContent = errorMessage;
                    replyForm.querySelector('.reply-content').classList.add('is-invalid');
                } else {
                    document.getElementById('commentFeedback').textContent = errorMessage;
                    document.getElementById('commentContent').classList.add('is-invalid');
                }
            }
        })
        .catch(error => {
            console.error('Error submitting comment:', error);
            const errorMessage = '提交失败，请重试';
            if (replyForm) {
                replyForm.querySelector('.reply-feedback').textContent = errorMessage;
                replyForm.querySelector('.reply-content').classList.add('is-invalid');
            } else {
                document.getElementById('commentFeedback').textContent = errorMessage;
                document.getElementById('commentContent').classList.add('is-invalid');
            }
        });
    }
    
    // 提交评论按钮事件
    const submitBtn = document.getElementById('submitComment');
    if (submitBtn) {
        submitBtn.addEventListener('click', function() {
            const content = document.getElementById('commentContent').value.trim();
            const feedbackElement = document.getElementById('commentFeedback');
            
            if (!content) {
                feedbackElement.textContent = '评论内容不能为空';
                document.getElementById('commentContent').classList.add('is-invalid');
                return;
            }
            
            submitComment(content);
        });
    }
    
    // 点赞评论功能
    function likeComment(commentId) {
        const csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
        
        fetch(`/interactive/comment/${commentId}/like/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken,
                'Content-Type': 'application/json'
            }
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('点赞失败');
            }
            return response.json();
        })
        .then(data => {
            if (data.status === 'success') {
                // 更新点赞计数
                const commentElement = document.querySelector(`[data-comment-id="${commentId}"]`);
                if (commentElement) {
                    const likeCount = commentElement.querySelector('.comment-like-count');
                    if (likeCount) {
                        likeCount.textContent = data.likes_count;
                    }
                    
                    // 更新点赞按钮样式
                    const likeBtn = commentElement.querySelector('.comment-like-btn');
                    if (likeBtn) {
                        if (data.liked) {
                            likeBtn.innerHTML = '<i class="bi bi-heart-fill text-danger"></i>';
                            likeBtn.classList.add('liked');
                        } else {
                            likeBtn.innerHTML = '<i class="bi bi-heart"></i>';
                            likeBtn.classList.remove('liked');
                        }
                    }
                }
            }
        })
        .catch(error => {
            console.error('点赞评论失败:', error);
            showFeedback('点赞失败，请重试');
        });
    }
    
    // 初始加载评论
    loadComments();
});
</script>

{% endblock %}

{% block extra_js %}
<script>
    // 点赞功能
    document.getElementById('like-btn').addEventListener('click', function() {
        const storyId = this.dataset.storyId;
        const button = this;
        button.disabled = true; // 防止重复点击
        
        // 预先更新UI，提供即时反馈
        const icon = button.querySelector('i');
        const isLiked = icon.classList.contains('bi-heart-fill');
        
        if (isLiked) {
            // 如果已点赞，立即切换为未点赞状态
            icon.classList.remove('bi-heart-fill');
            icon.classList.add('bi-heart');
            showFeedback('取消点赞中...');
        } else {
            // 如果未点赞，立即切换为点赞状态
            icon.classList.remove('bi-heart');
            icon.classList.add('bi-heart-fill');
            showFeedback('点赞中...');
        }
        
        fetch(`/story/${storyId}/like/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                if (data.liked) {
                    icon.classList.remove('bi-heart');
                    icon.classList.add('bi-heart-fill');
                    showFeedback('已点赞');
                } else {
                    icon.classList.remove('bi-heart-fill');
                    icon.classList.add('bi-heart');
                    showFeedback('已取消点赞');
                }
                
                // 更新所有点赞计数显示
                const likesCountElements = document.querySelectorAll('#likes-count');
                const likesBadge = document.querySelector('#likes-badge');
                
                likesCountElements.forEach(element => {
                    element.textContent = data.likes_count;
                });
                
                if (likesBadge) {
                    likesBadge.textContent = data.likes_count;
                }
            }
            button.disabled = false;
        })
        .catch(error => {
            console.error('点赞失败:', error);
            // 恢复原始状态
            if (isLiked) {
                icon.classList.remove('bi-heart');
                icon.classList.add('bi-heart-fill');
            } else {
                icon.classList.remove('bi-heart-fill');
                icon.classList.add('bi-heart');
            }
            showFeedback('操作失败，请重试');
            button.disabled = false;
        });
    });

    // 收藏功能
    document.getElementById('favorite-btn').addEventListener('click', function() {
        const storyId = this.dataset.storyId;
        const button = this;
        button.disabled = true; // 防止重复点击
        
        // 预先更新UI，提供即时反馈
        const icon = button.querySelector('i');
        const isFavorited = icon.classList.contains('bi-star-fill');
        
        if (isFavorited) {
            // 如果已收藏，立即切换为未收藏状态
            icon.classList.remove('bi-star-fill');
            icon.classList.add('bi-star');
            showFeedback('取消收藏中...');
        } else {
            // 如果未收藏，立即切换为收藏状态
            icon.classList.remove('bi-star');
            icon.classList.add('bi-star-fill');
            showFeedback('收藏中...');
        }
        
        fetch(`/story/${storyId}/favorite/`, {
            method: 'POST',
            headers: {
                'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value,
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                if (data.favorited) {
                    icon.classList.remove('bi-star');
                    icon.classList.add('bi-star-fill');
                    showFeedback('已收藏');
                } else {
                    icon.classList.remove('bi-star-fill');
                    icon.classList.add('bi-star');
                    showFeedback('已取消收藏');
                }
            }
            button.disabled = false;
        })
        .catch(error => {
            console.error('收藏失败:', error);
            // 恢复原始状态
            if (isFavorited) {
                icon.classList.remove('bi-star');
                icon.classList.add('bi-star-fill');
            } else {
                icon.classList.remove('bi-star-fill');
                icon.classList.add('bi-star');
            }
            showFeedback('操作失败，请重试');
            button.disabled = false;
        });
    });
    
    // 显示操作反馈
    function showFeedback(message) {
        const feedback = document.getElementById('action-feedback');
        feedback.textContent = message;
        feedback.style.opacity = 1;
        setTimeout(() => {
            feedback.style.opacity = 0;
        }, 2000);
    }
    
    // 复制链接功能
    document.getElementById('copy-link-btn').addEventListener('click', function() {
        const url = this.dataset.url;
        
        // 将传统复制方法放在函数中，方便复用
        function fallbackCopyTextToClipboard(text) {
            try {
                const tempInput = document.createElement('input');
                tempInput.style.position = 'fixed';
                tempInput.style.opacity = '0';
                tempInput.value = text;
                document.body.appendChild(tempInput);
                tempInput.focus();
                tempInput.select();
                
                const successful = document.execCommand('copy');
                document.body.removeChild(tempInput);
                if (successful) {
                    showFeedback('链接已复制到剪贴板');
                } else {
                    showFeedback('复制失败，请手动复制链接');
                    console.error('Fallback: 复制失败');
                }
            } catch (err) {
                showFeedback('复制失败，请手动复制链接');
                console.error('Fallback: 复制出错', err);
            }
        }

        // 首先检查Clipboard API是否存在
        if (!navigator.clipboard) {
            fallbackCopyTextToClipboard(url);
            return;
        }
        
        // 尝试使用Clipboard API
        try {
            navigator.clipboard.writeText(url)
                .then(() => {
                    showFeedback('链接已复制到剪贴板');
                })
                .catch(err => {
                    console.error('Clipboard API失败:', err);
                    fallbackCopyTextToClipboard(url);
                });
        } catch (err) {
            console.error('Clipboard API错误:', err);
            fallbackCopyTextToClipboard(url);
        }
    });
</script>
{% endblock %} 